package cn.sylinx.horm.spring.scan;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import cn.sylinx.horm.model.anno.Model;
import cn.sylinx.horm.util.GLog;

public class ModelScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware, EnvironmentAware {

	private ResourceLoader resourceLoader;
	private List<String> packages;
	private Environment environment;

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

		GLog.info("Starting ModelScannerRegistrar at:{}", new Date());
		
		Boolean cacheModelOnStart = environment.getProperty("hrom.config.cache-model-on-start", Boolean.class, false);
		if (!cacheModelOnStart.booleanValue()) {
			GLog.info("hrom.config.cache-model-on-start=false，无需扫描@Model");
			return;
		}
		
		Boolean debug = environment.getProperty("horm.config.debug", Boolean.class, false);
		if (debug.booleanValue()) {
			GLog.info("调试环境无需扫描@Model");
			return;
		}

		GLog.debug("Searching for model annotated with @Model");
		ClassPathModelScanner scanner = new ClassPathModelScanner(registry);
		try {
			if (this.resourceLoader != null) {
				scanner.setResourceLoader(this.resourceLoader);
			}
			scanner.setAnnotationClass(Model.class);
			scanner.registerFilters();
			scanner.doScan(StringUtils.toStringArray(getPackages()));

		} catch (IllegalStateException ex) {
			GLog.debug("Could not determine auto-configuration package, automatic model scanning disabled.", ex);
		}
	}

	public List<String> getPackages() {
		return packages;
	}

	public void setPackages(List<String> packages) {
		this.packages = packages;
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
}